#ifndef FILESCANNER_H
#define FILESCANNER_H

#include <head/g_pch_core.h>
#include "m_fhs.h"

class FileScanner : public QObject
{
    Q_OBJECT
public:
    explicit FileScanner(QObject *parent = nullptr):
        QObject(parent)
    {
        configTable = TD_CONFIG;
        table = GRIC_LOCATION;
        time_ = CurrentDateTime;
    }

    void prepareSources()
    {
        QStringList sources;
        QSqlQuery query;
        QString sql=QString("select detail from %1 where entry='%2'")
                .arg(configTable)
                .arg(SP_NAME);
        query.exec(sql);
        while (query.next()) {
            QString item=query.value(0).toString();
            sources.append(item);
        }

        if(sources.isEmpty())
        {
            qDebug() << "Info: Sources is Empty.";
            return;
        }

        executeScan(sources);
    }

    void do_scan(const QString &dirPath)
    {
        QSqlQuery query;
        QDirIterator dirIter(dirPath,QDir::Files,
                             QDirIterator::Subdirectories);

        QSqlDatabase::database().transaction();
        while (dirIter.hasNext()) {
            dirIter.next();

            QFileInfo item=dirIter.fileInfo();
            QString sql=QString("INSERT INTO %1 (time_,file_name,file_path,file_size) VALUES ('%2','%3','%4','%5')")
                    .arg(table)
                    .arg(time_)
                    .arg(item.baseName())
                    .arg(item.filePath())
                    .arg(item.size());
            query.exec(sql);
        }
        QSqlDatabase::database().commit();

        qDebug() << QString("Info: Source( %1 ) Scan Finished.").arg(dirPath);
    }

    void executeScan(const QStringList sources)
    {
        foreach (QString item, sources) {
            QFileInfo fileInfo(item);
            if(fileInfo.isFile())
            {
                qDebug() << QString("ERROR: Source( %1 ) is File.").arg(item);
                return;
            }

            if(!fileInfo.exists())
            {
                qDebug() << QString("ERROR: Source( %1 ) not Exists.").arg(item);
                return;
            }
            do_scan(item);
        }
    }

signals:

private:
    QString table;
    QString configTable;
    QString time_;
};

#endif // FILESCANNER_H
